#!/usr/bin/python3.6
import itchat, time
from itchat.content import *
from random import randint
import re
import requests
import json

tuling_key = '32cb7815ae5a41b88a27d88c6b265c2c'


def tuling(msg):
    r = requests.post('http://www.tuling123.com/openapi/api', {'key': tuling_key, 'info': msg})
    r = json.loads(r.content)
    if r['code'] == 100000:
        print(r['text'])
        return r['text']
    else:
        return '有点累了，待会再说'


@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    print(msg.type, msg.text)
    time.sleep(randint(3, 10))
    msg.user.send('[自动回复]抱歉，工作ing... ')


@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg.download(msg.fileName)
    typeSymbol = {
        PICTURE: 'img',
        VIDEO: 'vid',}.get(msg.type, 'fil')
    time.sleep(randint(3, 10))
    return '@%s@%s' % (typeSymbol, msg.fileName)


@itchat.msg_register(FRIENDS)
def add_friend(msg):
    msg.user.verify()
    time.sleep(randint(3, 10))
    msg.user.send('你好啊')


@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    groupid = msg.FromUserName
    print('msg=', msg)
    body = msg.Content
    chatroom = itchat.search_chatrooms(userName=groupid)
    memberList = chatroom['MemberList']
    print('memberList=', memberList)

    if msg.isAt:
        print('At=', msg)
        body = re.match(r'@(.*)\u2005(.*)', body, re.M | re.I)
        if body and body.group(2):
            body = body.group(2)
            time.sleep(randint(3, 10))
            r = tuling(body)
            msg.user.send('@%s %s' % (
                msg.actualNickName, r))


def qr_enc(msg):
    from MyQR import myqr
    import urllib
    msg = urllib.parse.quote(msg)
    version, level, qr_name = myqr.run(
        msg,
        version=1,
        level='H',
        picture='girl.jpg',
        colorized=True,
        contrast=1.0,
        brightness=1.0,
        save_name=None
    )
    return qr_name


if __name__ == "__main__":
    # itchat.auto_login(hotReload=True, picDir='/data/wxkf.png')
    # itchat.run(True)
    print(qr_enc('test啊啊aaa'))
